Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive sequence path.

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).

For example,

  1. 1
  2. \
  3. 3
  4. / \
  5. 2 4
  6. \
  7. 5

Longest consecutive sequence path is 3-4-5, so return 3.

  1. 2
  2. \
  3. 3
  4. /
  5. 2
  6. /
  7. 1

Longest consecutive sequence path is 2-3,not 3-2-1, so return 2.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. int max;
  12. public int longestConsecutive(TreeNode root) {
  13. max = 0;
  14. helper(root);
  15. return max;
  16. }
  17. int helper(TreeNode root) {
  18. if (root == null) return 0;
  19. int len = 1;
  20. int left = helper(root.left);
  21. int right = helper(root.right);
  22. if (root.left != null && root.val == root.left.val - 1) {
  23. len = Math.max(len, left + 1);
  24. }
  25. if (root.right != null && root.val == root.right.val - 1) {
  26. len = Math.max(len, right + 1);
  27. }
  28. max = Math.max(len, max);
  29. return len;
  30. }
  31. }